package com.woniuxy.driverschool.controller;/* *
@author author
@create 2021-09-29 20:21
*/

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.woniuxy.driverschool.entity.*;
import com.woniuxy.driverschool.service.RoleService;
import com.woniuxy.driverschool.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
public class UserController {

    private final static Log log = LogFactory.get();
    @Autowired
    UserService userService;

    @Autowired
    RoleService roleService;

    @GetMapping("/user")
    ResponseResult<List<User>> getDriverPackage(User user,String roleId){
        if(roleId!=""){
            Role role = roleService.getPeriodById(Integer.parseInt(roleId));
            user.setRole(role);
        }
        ResponseResult<List<User>> responseResult=new ResponseResult<List<User>>();
        responseResult.setData(userService.getUser(user));
        responseResult.setMessage("获取全部时段成功");
        responseResult.setState(200);
        return responseResult;
    }

//    @GetMapping("/driverPackage/{driverPackageId}")
//    ResponseResult<DriverPackage> getDriverPackageById(@PathVariable("driverPackageId") int driverPackageId){
//        ResponseResult<DriverPackage> responseResult=new ResponseResult<DriverPackage>();
//        responseResult.setData(driverPackageService.getDriverPackageById(driverPackageId));
//        responseResult.setMessage("获取全部时段成功");
//        responseResult.setState(200);
//        return responseResult;
//    }
//
    @PostMapping("/user")
    ResponseResult addUser(@RequestBody User user){
        user.setPassword("admin123");
        userService.addUser(user);

       ResponseResult responseResult=new ResponseResult();
       responseResult.setMessage("添加成功");
       responseResult.setState(200);
       return responseResult;
    }
//
    @PutMapping("/user")
    ResponseResult editUser(@RequestBody User user){
        userService.modifyUser(user);
        ResponseResult responseResult=new ResponseResult();
        responseResult.setMessage("修改成功");
        responseResult.setState(200);
        return responseResult;
    }

    @DeleteMapping("/user/{userId}")
    ResponseResult removeDriverPackage(@PathVariable("userId") int userId){
        System.out.println(userId+"-------------");
        userService.removeUserById(userId);
        ResponseResult responseResult=new ResponseResult();
        responseResult.setMessage("删除成功");
        responseResult.setState(200);
        return responseResult;
    }

    //    @GetMapping("/login")
//    ResponseResult<User> userLogin(String userName,String password){
//        System.out.println(userName);
//        System.out.println(password);
//        ResponseResult<User> responseResult=new ResponseResult<User>();
//        UsernamePasswordToken token=new UsernamePasswordToken(userName, password);
//        Subject subject= SecurityUtils.getSubject();
//        try {
//            subject.login(token);
//            responseResult.setMessage("登录成功");
//            responseResult.setState(200);
//        }catch (UnknownAccountException ex){
//            responseResult.setMessage("用户不存在");
//            responseResult.setState(401);
//        }catch (IncorrectCredentialsException ex){
//            responseResult.setMessage("密码不正确");
//            responseResult.setState(402);
//        }catch (AuthenticationException ex){
//            responseResult.setMessage("登录失败");
//            responseResult.setState(403);
//        }
//        return responseResult;
//    }
    @PostMapping("/login")
    Message4D2admin userLogin(@RequestBody String jsonstr, HttpServletRequest request) {

        log.debug("传过来的JSON串是:  {} ", jsonstr);
        // hutool 工具类来解析JSON串
        JSONObject jsonObject = JSONUtil.parseObj(jsonstr);

        String userName = (String) jsonObject.get("username");
        String password = (String) jsonObject.get("password");
        Message4D2admin<Object> message4D2admin = new Message4D2admin<>();
        UsernamePasswordToken token=new UsernamePasswordToken(userName, password);
        Subject subject= SecurityUtils.getSubject();

        HashMap<String, String> data = new HashMap<String, String>();
        message4D2admin.setData(data);
        try {
            subject.login(token);
            message4D2admin.setMsg("登录成功");
            message4D2admin.setCode(0);

            data.put("uuid", IdUtil.randomUUID());
            // token 前端建议一天更新一次
            String tk = request.getSession().getId();
            //String tk = IdUtil.randomUUID();
            data.put("token", tk);

            //Store.getMap().put(tk,subject);

            // 想从数据库中拿到名字
            data.put("name", userName);
        }catch (UnknownAccountException ex){
            message4D2admin.setMsg("用户不存在");
            message4D2admin.setCode(401);
        }catch (IncorrectCredentialsException ex){
            message4D2admin.setMsg("密码不正确");
            message4D2admin.setCode(402);
        }catch (AuthenticationException ex){
            message4D2admin.setMsg("登录失败");
            message4D2admin.setCode(403);
        }
        log.debug("response:{}", message4D2admin);
        return message4D2admin;
    }

}
